package com.dc.designPattern._2_factory.extend.extend2;

import com.google.common.collect.Maps;

import java.util.Map;
import java.util.Objects;

/**
 * Description: 延迟加载_工厂类
 *
 *  一个对象被消费完毕后，并不立刻释放，工厂类保持其初始状态，等待再次被使用
 *
 * @author: gdc
 * @date: 2021/6/21
 * @version 1.0
 */
public class ProductFactory {

    private static Map<String, Product> productMap = Maps.newHashMap();

    public static Product getInstance(String type) {
        Product product;

        if (productMap.containsKey(type)) {
            product = productMap.get(type);
        } else {
            if (Objects.equals("product1", type)) {
                product = new ConcreteProduct1();
            } else if (Objects.equals("product2", type)) {
                product = new ConcreteProduct2();
            } else {
                throw new IllegalArgumentException("传入的参数有误");
            }

            // 同时把对象放到缓存容器中
            productMap.put(type, product);
        }

        return product;
    }
}
